package com.hsytech.baoinbao.waste;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.hsytech.baoinbao.AdapterListView;
import com.hsytech.baoinbao.R;
import com.hsytech.baoinbao.SharedPreferencesTools;
import com.hsytech.baoinbao.base.BaseActivity;
import com.hsytech.baoinbao.gsondata.GsonUtil;
import com.hsytech.baoinbao.gsondata.RecyclingManStockData;
import com.hsytech.baoinbao.volleytool.ApiUrls;
import com.hsytech.baoinbao.volleytool.HttpUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 123 on 2016/3/11.
 */
public class ListWasteActivity extends BaseActivity implements AdapterView.OnItemClickListener, ExpandableListView.OnChildClickListener {
    private ExpandableListView expandableListView;
    private Handler handler = new Handler();
    private LinearLayout yes, no;
    private AlertDialog builderSuccess, builderError, builder = null;
    private Intent intent;
    private String phone;
    private TextView nameTextView, phoneTextView;
    private AdapterListView adapterListView;
    private RecyclingManStockData dataHttp;
    private RecyclingManStockData dataHttpDest;
    private HttpUtil.HttpCallback httpCallback = new HttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, JSONObject response) {

            dataHttp = GsonUtil.fromJson(response.toString(), RecyclingManStockData.class);
            dataHttpDest = GsonUtil.fromJson(response.toString(), RecyclingManStockData.class);

            nameTextView.setText(dataHttp.getResult().getRecycling_man().getName());
            phoneTextView.setText(dataHttp.getResult().getRecycling_man().getUser_name());
            adapterListView = new AdapterListView(getApplicationContext(), dataHttp, dataHttpDest);
            expandableListView.setAdapter(adapterListView);
//            1、首次加载全部展开：
            int groupCount = expandableListView.getCount();

            for (int i = 0; i < groupCount; i++) {

                expandableListView.expandGroup(i);

            }
            ;
//            提醒：加载前别忘了判断adapter是否为空和有没有Group数据哦、

//            2、不能点击收缩：

//            expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//
//                @Override
//                public boolean onGroupClick(ExpandableListView parent, View v,
//                                            int groupPosition, long id) {
//                    // TODO Auto-generated method stub
//                    return true;
//                }
//            });
//            把他的组点击事件屏蔽、

        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            showToast(R.string.msg_http_failure);
        }

        @Override
        public void onErrorMsg(int what, String msg) {
            showToast(msg);
        }
    };
    private HttpUtil.HttpCallback httpCallback1 = new HttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, JSONObject response) {
            Log.d("mylog", "success" + response);
            showDialogSuccess();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    builderSuccess.dismiss();
                    ListWasteActivity.this.finish();
                }
            }, 2000);
        }

        @Override
        public void onError(int what, int type, VolleyError error) {

        }

        @Override
        public void onErrorMsg(int what, String msg) {
            showDialogError();
            showToast(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waste_list);
        setCenterTitleText("废品入库");
        setLeft_button(true);
        setRightBtn(true);
        intent = getIntent();
        phone = intent.getStringExtra("phone");
        nameTextView = F(R.id.name);
        phoneTextView = F(R.id.phone);
        expandableListView = (ExpandableListView) findViewById(R.id.mListView);
        initExpandListView();

    }

    private boolean checkWindows() {
        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            //            隐藏软键盘
            //            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            return true;
        } else {

            return false;
        }

    }


    private void initExpandListView() {
        expandableListView.setOnItemClickListener(this);
        expandableListView.setOnChildClickListener(this);
        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getWindow().getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }
        });

        expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Map<String, String> data = new HashMap<>();
        data.put("token", SharedPreferencesTools.getTOKEN(this));
        data.put("user_name_re", phone);
        HttpUtil.httpGetWithParams(0, ApiUrls.RECYCLING_MAN_STOCK + "?user_name_re=" + phone + "&token=" + SharedPreferencesTools.getTOKEN(this), data, httpCallback, ListWasteActivity.this);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    }

    @Override
    public void onMenuRightBtn() {
        super.onMenuRightBtn();
        showDialog();

    }


    public void showDialog() {
        builder = new AlertDialog.Builder(ListWasteActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog, (ViewGroup) findViewById(R.id.dialog_parent));
//        builder.setView(layout);
        builder.show();
        builder.setCancelable(false);
        builder.getWindow().setContentView(layout);
        yes = (LinearLayout) layout.findViewById(R.id.yes);
        no = (LinearLayout) layout.findViewById(R.id.no);


        yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                for (int i = 0; i < dataHttpDest.getResult().getStorage().size(); i++) {
                    for (int j = 0; j < dataHttpDest.getResult().getStorage().get(i).getChildren().size(); j++) {
                        if (dataHttpDest.getResult().getStorage().get(i).getChildren().get(j).getStock().equals("")) {
                            dataHttpDest.getResult().getStorage().get(i).getChildren().get(j).setStock("0");
                        }
                    }
                }

                Map<String, String> data = new HashMap<>();
                data.put("token", SharedPreferencesTools.getTOKEN(ListWasteActivity.this));
                data.put("data", GsonUtil.toJson(dataHttpDest.getResult()));
                data.put("recycling_man_id", dataHttpDest.getResult().getRecycling_man().getId());
                Log.d("mylog", " GsonUtil.toJson(dataHttp.getResult())" + GsonUtil.toJson(dataHttpDest.getResult()));
                Log.d("mylog", " recycling_man_id" + dataHttpDest.getResult().getRecycling_man().getId());
                HttpUtil.httpPostWithParams(0, ApiUrls.STORAGE_OK, data, httpCallback1, ListWasteActivity.this);


            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();
            }
        });

    }

    public void showDialogSuccess() {
        builderSuccess = new AlertDialog.Builder(ListWasteActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog2, (ViewGroup) findViewById(R.id.dialog_parent));
//        builder.setView(layout);
        builderSuccess.show();
        builderSuccess.setCancelable(false);
        builderSuccess.getWindow().setContentView(layout);
    }

    public void showDialogError() {
        if (builder.isShowing()) {
            builder.dismiss();
        }
        builderError = new AlertDialog.Builder(ListWasteActivity.this).create();
        LayoutInflater inflater = LayoutInflater.from(this);
        //获取相关的布局
        View layout = inflater.inflate(R.layout.dialog2, (ViewGroup) findViewById(R.id.dialog_parent));
        TextView name = (TextView) layout.findViewById(R.id.name);
        name.setText("没有入库商品");
//        builder.setView(layout);
        builderError.show();
        builderError.setCancelable(true);
        builderError.getWindow().setContentView(layout);
    }


    @Override
    public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {

//        showDialogEdit(dataHttp.getResult().getStorage().get(i).getChildren().get(i1).getCat_name(), dataHttp.getResult().getStorage().get(i).getChildren().get(i1).getUnit(), i, i1);

        return false;
    }
}
